#!/usr/bin/env python

__author__ = "Senthil Kumaran"

import random
import logging
import urllib2
import BeautifulSoup

import wsgiref.handlers
from google.appengine.ext import webapp

from yos.crawl.rest import download
from yos.util import text, console
from yos.boss import ysearch
from yos.yql import udfs, db

from django.utils import simplejson

questions = [
"What is happening with, {buzz}?",
"Why is {buzz} is in the news?",
"What happened with {buzz}, Watson?",
"Mrs. Hudson, was talking about {buzz}. What is the matter Dear Watson",
"The world seem to be concerned about {buzz}, why is it so Watson",
"What really is the matter with {buzz}, Watson?",
"Watson, what is the news about {buzz}?",
"Why is {buzz} is in the news?",
"I was thinking about Irene Adler on this Valentine, but this {buzz} bothers me.",
"What happened with {buzz}, Watson?",
]

OPENING = ["""In choosing a few typical cases which illustrate the remarkable
mental qualities of my friend, Sherlock Holmes, I have endeavoured, as far as
possible, to select those which presented the minimum of sensationalism, while
offering a fair field for his talents.  It is, however, unfortunately impossible
entirely to separate the sensational from the criminal, and a chronicler is left
in the dilemma that he must either sacrifice details which are essential to his
statement and so give a false impression of the problem, or he must use matter
which chance, and not choice, has provided him with.  He asked me one day,
Watson,""",
"""
In the third week of November, in the year 2009, a dense yellow fog
settled down upon London.  From the Monday to the Thursday I doubt
whether it was ever possible from our windows in Baker Street to see
the loom of the opposite houses.  The first day Holmes had spent in
cross-indexing his huge book of references. He asked quite inadvertently,
""",
"""
Holmes paced restlessly about our sitting-room in a fever of
suppressed energy, biting his nails, tapping the furniture, and chafing against
inaction. He came near by and queried,
""","""
Mrs. Hudson, the landlady of Sherlock Holmes, was a long-suffering
woman.  Not only was her first-floor flat invaded at all hours by
throngs of singular and often undesirable characters but her remarkable
lodger showed an eccentricity and irregularity in his life which must
have sorely tried her patience. His incredible untidiness, his
addiction to music at strange hours, his occasional revolver practice
within doors, his weird and often malodorous scientific experiments,
and the atmosphere of violence and danger which hung around him made
him the very worst tenant in London.   On this, Holmes asked on a related
case.""" ,

""" In recording from time to time some of the curious experiences and
interesting recollections which I associate with my long and intimate
friendship with Mr. Sherlock Holmes, I have continually been faced by
difficulties caused by his own aversion to publicity. But to keep himself abrest
of the rumor going around, he asked me."""]

answers = [
"I replied,",
"I have to say,",
"Holmes that is,"
"Well,",
"I know that",
"I Informed Holmes about",
"Okay,",
"That is,"
"Answer to that would be",
"I replied again"]

TITLES = [
'The Adventure of the  {buzz}',
'The Mysteries of a {buzz}',
'{buzz} and Other Stories ',
'Being The Tragedy Of {buzz}',
'The Disappearance of {buzz}',
'The Doings of {buzz}',
'The Exploits of {buzz}',
'The Great {buzz}',
'The Great Shadow and Other Napoleonic Tales ',
'The Hound of the {buzz}',
'The Lock and Key ',
'The Lost World ',
'The Memoirs of {buzz}',
'His Statement as made to {buzz}',
'{buzz}, The Murderer ',
'The Mystery of {buzz}',
'The Return of Sherlock Holmes at {buzz}',
'The Sign of the {buzz}',
'The Stark Munro Letters ',
'A Study in {buzz}',
'The Tragedy of the {buzz}',
'A Memory of the {buzz}',
'The War in {buzz}',
'The White {buzz}']

class NewsSearchHandler(webapp.RequestHandler):
  def __init__(self):
    page = urllib2.urlopen('http://buzz.yahoo.com')
    soup = BeautifulSoup.BeautifulSoup(page.read())
    buzzlist = soup.find('table',id='top-searches')
    self.tags = []
    for mover in buzzlist.findAll('td'):
        if mover and mover.a:
            self.tags.append(mover.a.renderContents())

    title = random.choice(TITLES)
    self.story = title.replace('{buzz}',random.choice(self.tags))
    self.opening = random.choice(OPENING)

  def get(self):
    self.response.out.write('<html><body>')
    self.response.out.write('<br><br><h1>' + self.story + '</h1></br></br>')
    self.response.out.write(self.opening)
    for item in self.tags:
        data = ysearch.search(item, vertical="news",count=1)
        news = db.create(data=data)
        question = random.choice(questions).replace('{buzz}',item)
        self.response.out.write(question)
        self.response.out.write('<br>')
        response = random.choice(answers)
        self.response.out.write(response)
        serialized = simplejson.dumps(news.rows[0]['abstract'])
        self.response.out.write(serialized)
        self.response.out.write('<br>')
    end = 'That was the end of ' + self.story
    self.response.out.write('<br>')
    self.response.out.write(end)
    self.response.out.write('</html></body>')


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication([('/', NewsSearchHandler),
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
